#!/usr/bin/python
# -*- coding: UTF-8 -*-
# @License: Copyright © 2019 代鹏. All rights reserved.
# @Author: 代鹏
# @Contact: 272481080@qq.com
# @File: make_number.py
# @Date: 2019/9/09
# @Software：cu
# @description :make up the number 凑数、充数
from flask import jsonify, request, Blueprint
from app.server.http_beta import add_headers
import sys

make_number = Blueprint('make_number', __name__)
# 最小差额平方，预制一个大数
min1 = sys.float_info.max
# 最终列表
R = []


def init():
    global min1, R
    min1 = sys.float_info.max
    R = []

@make_number.route('/mn', methods=['GET', 'POST'])
def make_n():
    init()  # 初始化
    data = request.get_json()
    datas = data['datas']
    f_datas = []
    for d in datas.split(','):
        f_datas.append(float(d))
    amount = float(data['amount'])
    resp = dict()
    if f_datas and amount:
        exec_mn(f_datas, amount)
        r_sum = sum(R)
        r_min = r_sum - amount
        if R:
            resp['status'] = 0
            data = dict()
            data['result'] = R
            data['r_sum'] = r_sum
            data['r_min'] = r_min
            resp['data'] = data
        else:
            resp['status'] = 1
            resp['msg'] = 'name or password error!'
    return add_headers(jsonify(resp))


def exec_mn(datas,tar):
    # 金额列表
    A = datas
    # A = [243.48, 16.97, 1986.26, 740.4, 360, 2086.94, 372, 789.25, 260.37, 28.15, 400, 1072, 1020, 6600, 2332, 11640, 2,
    #      224.54, 19.59, 360, 2023.9, 788.93, 12.06, 5346]
    # 目标金额
    target = tar
    # target = 12535.67

    def abc(B, TR, nu):
        # 嵌套函数
        # B:订单列表
        # TR:临时列表
        # nu:列表下标，也是递归层级
        # 确保每一层的列表独立
        b = B
        tr = TR[:]
        global min1, R
        for j in range(len(b)):
            if min1 == 0:
                break
            tr[nu] = b[j]  # 向列表中增加一个数
            if nu < num - 1:
                abc(b[j + 1:], tr, nu + 1)
            else:
                min2 = (sum(tr) - target) ** 2
                if min2 < min1:  # 如果找到更小的就替换
                    R = tr[:]
                    min1 = min2
                    print('update R:%s,min:%s' % (R, min1))  # 输出替换的数值

    # 开始
    for i in range(1, len(A) + 1):
        if min1 == 0:
            break
        num = i
        TR = [0] * num
        print('TR:%s' % TR)
        # abc(A[:], TR, 0)
        abc(A, TR, 0)
    print('min1:%s' % min1)
    print('list:%s' % R)
    print('sum:%s' % sum(R))


if __name__ == "__main__":
    ds = '100，200，300，400,500'
    exec_mn()
